﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Text.Json;
using Xc.DataAccess.Core;

namespace Xc.WaterMeters.ServerHosts.Services
{
    /// <summary>
    /// 修改配置文件服务
    /// </summary>
    public class ModifyAppSettingService : IModifyAppSettingService
    {
        private readonly IWebHostEnvironment webHostEnvironment;
        public ModifyAppSettingService(IWebHostEnvironment webHostEnvironment)
        {
            this.webHostEnvironment = webHostEnvironment;
        }
        /// <summary>
        /// 更新配置文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="saveData"></param>
        /// <returns></returns>
        public Result UpdateSettingFile<T>(T saveData)
        {
            try
            {
                var file = Path.Combine(webHostEnvironment.ContentRootPath, "appsettings.json");
                var text = System.Text.Json.JsonSerializer.Serialize(saveData, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(file, text);
                return Result.Accept("保存成功");
            }
            catch (System.Exception err)
            {
                return Result.Reject(err.Message);
            }
        }
    }
}
